package com.example.base.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import kotlin.math.abs

/**  解决与 ViewPager 滑动冲突的 SwipeRefreshLayout  **/
class ViewPagerSwipeRefreshLayout : SwipeRefreshLayout {

    private var mTouchSlop: Int = 0

    constructor(context: Context) : super(context)

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        mTouchSlop = ViewConfiguration.get(context).scaledTouchSlop
    }

    private var mStartX: Float = 0f
    private var mStartY: Float = 0f
    private var mIsVpDrag = false

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mStartX = ev.x
                mStartY = ev.y
                mIsVpDrag = false
            }
            MotionEvent.ACTION_MOVE -> {
                if (mIsVpDrag) return false
                val endX = ev.x
                val endY = ev.y
                val distanceX = abs(endX - mStartX)
                val distanceY = abs(endY - mStartY)
                if (distanceX > mTouchSlop && distanceX > distanceY) {
                    mIsVpDrag = true
                    return false
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> mIsVpDrag = false
        }
        return super.onInterceptTouchEvent(ev)
    }

}